<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .container {
        width: 300px;
        position: relative;
      }
      .textarea {
        width: 100%;
      }
      .count {
        position: absolute;
        right: 0;
        bottom: 0;
        color: #999;
      }
      .comment-list {
        width: 300px;
        border: 1px solid #000;
        padding: 10px;
        margin-top: 10px;
      }
      .comment {
        width: 100%;
        padding: 10px;
        margin-bottom: 10px;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <textarea class="textarea" name="" id="" cols="30" rows="10"></textarea>
      <p class="count">0/100</p>
    </div>
    <button class="btn">发布评论</button>

    <!-- 评论列表  -->
    <div class="comment-list">
      <div class="comment">
        <p style="display: none">评论内容</p>
      </div>
    </div>

    <script>
      const textarea = document.querySelector("textarea");
      const p = document.querySelector("p");
      // input：用户输入触发
      textarea.addEventListener("input", () => {
        const len = textarea.value.length;
        p.textContent = `${len}/100`;
        if (len > 100) {
          textarea.value = textarea.value.slice(0, 100);
          p.textContent = `100/100`;
        }
      });
      textarea.addEventListener("keydown", (e) => {
        if (e.key === "Enter") {
          btn.click();
        }
      });
      const btn = document.querySelector("button");
      btn.addEventListener("click", () => {
        const comment = textarea.value;
        // 如果用户输入的不为空，则发布评论
        //  trim() 去除字符串两端的空格
        if (comment.trim() !== "") {
          const commentItem = document.querySelector(".comment p");
          commentItem.innerHTML = comment;
          commentItem.style.display = "block";
          // 清空textarea
          textarea.value = "";
          p.textContent = `0/100`;
        } else {
          alert("请输入评论内容");
        }

        // 箭头函数中this指向window
        console.log(this);
      });

      btn.addEventListener("click", function () {
        // this: 当前触发事件的元素
        console.log(this);
        this.style.color = "red";
      });
    </script>
  </body>
</html>
